import 'dart:io';

import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:shared_preferences/shared_preferences.dart';

class MinePage extends StatefulWidget {
  @override
  _MinePageState createState() => _MinePageState();
}

class _MinePageState extends State<MinePage> {

  File _image;
  File _albumImage;

  bool state = true;
  int currentIndex = 0;

  @override
  void initState() {
    super.initState();
    _incrementcounter();
  }

  Future getImage() async {
    state = !state;
    var image = await ImagePicker.pickImage(source: state ? ImageSource.camera : ImageSource.gallery);
    setState(() {
      if(state == false){
        _albumImage = image;
      } else {
        _image = image;
      }
    });
  }


  _incrementcounter() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    int counter = (prefs.getInt('counter') ?? 0) + 1;
    setState(() {
      currentIndex = counter;
    });

    await prefs.setInt("counter", currentIndex);
  }

  @override
  Widget build(BuildContext context) {
    final List<Widget> widgets = [
      Text("$currentIndex"),
      ExpansionTile(
        title: Icon(Icons.add),
        leading: Text("Section"),
        children: <Widget>[
          Text("chil1"),
          Text("chil2"),
          Text("chil3"),
          Text("chil4")
        ],
      )
    ];
    if (_image != null) {
      widgets.add(
        Container(
          height: 100,
          child: Image.file(_image),
        ),
      );
    }
    if (_albumImage != null) {
      widgets.add(
        Container(
          height: 100,
          child: Image.file(_albumImage),
        )
      );
    }
    return Scaffold(
      appBar: AppBar(
        title: Text("Image Picker example"),
      ),
      body: Column(
        children: widgets,
      ),
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.add_a_photo),
        onPressed: getImage,
      ),
    );
  }
}